<?php

namespace app\api\controller;

use app\admin\model\Imessage;
use app\common\controller\Api;
use think\Db;

/**
 * 会员中心接口
 */
class Usercenter extends Api
{

    //  不需要登录的接口
    protected $noNeedLogin = ['index','login', 'mobilelogin', 'register', 'resetpwd', 'third' , 'getEmsChangeEmail','call_center' ];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心主页
     */
    public function index()
    {
        $user = $this->auth->getUser();
        //  处理需要的字段
        $needField = ['id','nickname','avatar','invite_code','enable','cash_money','cloud_money','cloud_money_freeze','cloud_money_register','cloud_money_other','cloud_money_release'];
        foreach ($needField as $k) $needField[$k] = $k;
        //
        $result = ['earnings'=>0,'cash_money'=>0,'cloud_money'=>0,'enable'=>0,'is_login'=>0];
        //  如果登录
        if ($user)
        {
            foreach ($user->getData() as $k=>$v){
                if (isset($needField[$k]))
                    $result[$k] = $v;
            }
            //  查询累计收益
            $where = ['user_id' => $user->id,'type' => config('CashType.ExchangeIn')];  //  查询类型为交易收入的
            $earnings = Db::name('cash_log')->where($where)->sum('value');
            $result['earnings'] = round($earnings,2);   //  保留两位小数
            $result['is_login'] = 1;
        }
        if (isset($result['avatar']))
        {
            $result['avatar'] = $result['avatar'] ? $result['avatar'] : config('site.default_avatar');
        }
        $result['total_cloud_money'] = $user->cloud_money + $user->cloud_money_freeze + $user->cloud_money_register + $user->cloud_money_other + $user->cloud_money_release;
        $this->success('个人中心', $result);
    }

    /*
     * 用户实名认证状态
     * */
    public function realAuth(){
        $user = $this->auth->getUser();

        $auth_result = Db::name('user_auth')
            ->field('images,uptime,audit_time,direction,reason,status')
            ->where(['user_id'=>$user->id,'type'=>1])
            ->select();

        if (empty($auth_result)) $this->error('您还没有实名认证',['status'=>0]);

        //  如果已经上传
        $data = [];
        foreach ($auth_result as $item){
            $item['images'] = $this->request->domain().$item['images'];
            if ($item['direction'] == 'front'){
                $data['front'] = $item;
            }else{
                $data['back'] = $item;
            }
        }
        if ($user->is_realname == 1) {
            $data['status'] = 1;
            $this->success('您已完成实名认证',$data);
        }else{
            $auth_result_0 = $auth_result[0];
            if ($auth_result_0['status'] == 0)
            {
                $data['status'] = 2;
                $this->success('您已经上传，请耐心等待审核',$data);
            }
            else if ($auth_result_0['status'] == -1) $this->error('身份认证失败,原因'.$auth_result_0['reason'],['status' => -1]);
            else $this->error('身份认证失败，请联系客服',['status' => -1]);
        }
    }


    /*
     * 用户实名认证图片上传
     * */
    public function realAuthUpload(){
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'UserCenter.realname');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $realname = $this->request->request('realname');
        $id_number = $this->request->request('idnumber');
        $front = $this->request->file('IDFront');
        $back = $this->request->file('IDBack');

        if (!$front || !$back) $this->error('请上传完整正反面图片');

        //  判断是否已经上传
        $auth_log =Db::name('user_auth')->where(['user_id'=>$user->id,'type'=>1,'status'=>0])->find();
        if ($auth_log)
        {
            $this->error('您已经上传，请耐心等待审核',['status' => 2]);
        }


        //  上传路径
        $auth_path = get_path('auth');
        $info_f = $front->move(substr($auth_path,1,strlen($auth_path)));
        $info_b = $back->move(substr($auth_path,1,strlen($auth_path)));

        if ($info_f && $info_b){
            // 成功上传后 获取上传信息
            $front_path = str_replace("\\",'/',$auth_path.$info_f->getSaveName());
            $back_path = str_replace("\\",'/',$auth_path.$info_b->getSaveName());
            //  插入数据库等待审核
            Db::startTrans();
            try{
                $now = time();
                Db::name('user_auth')->insertAll([
                    ['user_id'=>$user->id,'images'=>$front_path,'direction'=>'front','type'=>1,'status'=>0,'uptime'=>$now],
                    ['user_id'=>$user->id,'images'=>$back_path,'direction'=>'back','type'=>1,'status'=>0,'uptime'=>$now]
                ]);
                Db::name('user')->where('id','=',$user->id)->update(['is_realname' => 0,'realname' => $realname,'id_number' => $id_number]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
            $this->success('身份认证已经上传，请耐心等待审核',['status' => 2]);
        }else{
            // 上传失败获取错误信息
            $this->error($front->getError()) or $this->error($back->getError());
        }
    }

    /*
     * 用户认证
     * */
    public function real_auth()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'UserCenter.realname');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $realname = $this->request->request('realname');
        $id_number = $this->request->request('idnumber');
        $front_path = $this->request->request('IDFront');
        $back_path = $this->request->request('IDBack');

        if (!$front_path || !$back_path) $this->error('请上传完整正反面图片');

        //  判断是否已经上传
        if (Db::name('user_auth')->where(['user_id'=>$user->id,'type'=>1,'status'=>0])->find()) $this->success('您已经上传，请耐心等待审核',['status' => 2]);

        //  上传路径
        /*$auth_path = get_path('auth');
        $info_f = $front->move(substr($auth_path,1,strlen($auth_path)));
        $info_b = $back->move(substr($auth_path,1,strlen($auth_path)));*/

        //  事务提交
        Db::startTrans();
        try{
            $now = time();
            Db::name('user_auth')->insertAll([
                ['user_id'=>$user->id,'images'=>$front_path,'direction'=>'front','type'=>1,'status'=>0,'uptime'=>$now],
                ['user_id'=>$user->id,'images'=>$back_path,'direction'=>'back','type'=>1,'status'=>0,'uptime'=>$now]
            ]);
            Db::name('user')->where('id','=',$user->id)->update(['is_realname' => 0,'realname' => $realname,'id_number' => $id_number]);
            Db::commit();
            $this->success('身份认证已经上传，请耐心等待审核',['status' => 2]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e);
        }
    }

    /*
     * 查询账户信息
     * */
    public function get_user_info()
    {
        $user = $this->auth->getUser();
        //  处理需要的字段
        $needField = ['id', 'username', 'nickname', 'mobile', 'avatar', 'cash_money','cloud_money','cloud_money_freeze','cloud_money_register','cloud_money_other','cloud_money_release','cloud_money_released',
            'wechat_id','alipay_id','bank_card','bank_card_name','bank_card_address','realname','id_number'];
        foreach ($needField as $k) $needField[$k] = $k;
        //
        $result = ['earnings'=>0,'cash_money'=>0,'cloud_money'=>0,'enable'=>0,'is_login'=>0];
        //  如果登录
        if ($user) {
            foreach ($user->getData() as $k => $v) {
                if (isset($needField[$k]))
                    $result[$k] = $v;
            }
            $where = ['user_id' => $user->id,'type' => config('CashType.ExchangeIn')];  //  查询类型为交易收入的
            $earnings = Db::name('cash_log')->where($where)->sum('value');
            $result['earnings'] = round($earnings,2);   //  保留两位小数
            $result['is_login'] = 1;

        }
        if (isset($result['avatar']))
        {
            $result['avatar'] = $result['avatar'] ? $result['avatar'] : config('site.default_avatar');
        }
        $result['total_cloud_money'] = $user->cloud_money + $user->cloud_money_freeze + $user->cloud_money_register + $user->cloud_money_other + $user->cloud_money_release;
        $this->success('用户信息',$result);
    }

    /*
     * 修改昵称
     * */
    public function changeNickname(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.newnickname');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $newNickname = $this->request->request('new_nickname');

        $user->nickname = $newNickname;
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }
    /*
     * 修改用户头像
     * */
    public function change_user_avatar()
    {
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.avatar');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $avatar = $this->request->request('avatar_url');

        $user->avatar = $avatar;
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');

    }

    /*
     * 修改微信号
     * */
    public function changeWechat(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.new_wechat');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $newWechat = $this->request->request('new_wechat');

        $user->wechat_id = $newWechat;
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }/*
     * 修改支付宝
     * */
    public function changeAlipay(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.new_alipay');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $newAlipay = $this->request->request('new_alipay');

        $user->alipay_id = $newAlipay;
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }
    /*
     * 修改银行卡信息
     * */
    public function changeBankInfo(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.new_bank_info');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $bank_card = $this->request->request('bank_card_num');
        $bank_card_name = $this->request->request('bank_card_name');
        $bank_card_address = $this->request->request('bank_card_address');

        $user->bank_card = $bank_card;
        $user->bank_card_name = $bank_card_name;
        $user->bank_card_address = $bank_card_address;

        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }

    /*
     * 检测支付密码是否为空
     * */
    public function check_pay_password()
    {
        $user = $this->auth->getUser();
        $pay_password = $user->pay_password;
        if (!isset($pay_password) || empty($pay_password) || strlen($pay_password) < 16)
            $this->error('支付密码未设置');
        else
            $this->success('已设置支付密码');
    }

    /*
    * 修改支付密码
    * */
    public function change_pay_password(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.new_pay_password');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $old_pay_password = $this->request->request('old_pay_password');
        $new_pay_password = $this->request->request('new_pay_password');
        $verify_pay_password = $this->request->request('verify_pay_password');
        if ($new_pay_password !== $verify_pay_password)
        {
            $this->error('两次密码输入不一致');
        }
        //  验证密码是否正确
        if (!empty($user->pay_password) && $this->auth->getEncryptPassword($old_pay_password,$user->salt) !== $user->pay_password)
        {
            $this->error('支付密码不正确');
        }

        $user->pay_password = $this->auth->getEncryptPassword($new_pay_password,$user->salt);
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }
    /*
     * 修改密码
     * */
    public function change_password(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'UserCenter.new_password');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $old_password = $this->request->request('old_password');
        $new_password = $this->request->request('new_password');
        $verify_password = $this->request->request('verify_password');
        if ($new_password !== $verify_password)
        {
            $this->error('两次密码输入不一致');
        }
        //  验证密码是否正确
        /*if ($this->auth->getEncryptPassword($old_password,$user->salt) !== $user->password)
        {
            $this->error('登录密码不正确');
        }
        $user->password = $this->auth->getEncryptPassword($new_password,$user->salt);*/

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($new_password, $old_password, false);
        if ($ret)
        {
            $this->success('密码修改成功');
        }
        else
        {
            $this->error($this->auth->getError());
        }

        /*if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');*/
    }

    /*
     * 客服中心
     * */
    public function call_center(){
        $imessage = new Imessage();
        $where['status']  =  config('ArticleStatus.Show');
        $where['type']  =   config('ArticleType.Service');
        $field = 'id,title,content,time,view,user_id';

        $service = $imessage
            ->field($field)
            ->where($where)
            ->order('time desc')
            ->find();

        if(!$service)   $this->success('暂时没有客服','暂时没有客服');
        $data = $service->getData();
        $data['nickname'] = $service->user->nickname;
        $data['time_text'] = $service->time_text;

        $this->success('客服中心',$data);
    }

    /*
     * 我的团队
     * */
    public function my_team(){
        $validate_result = $this->validate($this->request->request(),'UserCenter.my_team');
        if ($validate_result !== true)$this->error($validate_result);

        $user = $this->auth->getUser();
        $uid = $user->id;
        $level = $this->request->request('level');

        $invite_user_list =
            Db::name('user_invite_log l')
            ->field('u.avatar,u.id,u.nickname,u.invite_code mobile,u.jointime')
            ->where('invite_'.$level,'=',$uid)
            ->join('user u','u.id = l.user_id','left')
            ->select();
        foreach ($invite_user_list as $k=>$v){
            $v['avatar'] = $v['avatar'] ? $v['avatar'] : '/assets/img/avatar.png';
            $invite_user_list[$k]['avatar'] = $this->request->domain() . $v['avatar'];    //  拼接url

            $invite_user_list[$k]['jointime'] = date('Y-m-d H:i:s',$v['jointime']);
        }


        //  四级推荐的分别人数
        $tmp['total_count'] = 0;
        for ($i=1;$i<=4;$i++)
        {
            $tmp['count_'.$i] = \db('user_invite_log')->where('invite_'.$i,'=',$uid)->count();
            $tmp['total_count'] += $tmp['count_'.$i];//  四级总人数
        }

        $data = [
            'nickname'  =>  $user->nickname,
            'avatar'    =>  $user->avatar,
            'mobile'  =>  $user->mobile,
            'jointime'  =>  date('Y-m-d H:i:s',$user->jointime),
            'list'  =>  $invite_user_list,
        ];
        $data = array_merge($tmp,$data);
        $this->success('推荐人列表',$data);
    }


    /*
     * 获取推广二维码
     * */
    public function getGeneralizeQrcode(){
        $user = $this->auth->getUser();
//        $user = User::get(3);
        $invite_code = $user->invite_code;  //  用户邀请码
        //  拼接邀请链接界面
        $invite_url = $this->request->domain();
        $invite_url .= '/Html/te/login/register.html';
        $invite_url .= '?invite_code='.$invite_code;

        $label = '我的邀请码：'.$invite_code; //  二维码上的文字
        $label = ''; //  二维码上的文字
        $qrcode = create_qrcode($invite_url,md5(time().$invite_code),$label);   //  生成的二维码地址
        $qrcode_url = /*$this->request->domain() . */'/' . $qrcode;

        $result = [
            'invite_code' => $invite_code,
            'qrcode_url' => $qrcode_url,
            'invite_url' => $invite_url,
            ];
        $this->success('获取成功',$result);
    }

    /*
     * 获取推广链接
     * */
    public function getGeneralizeUrl(){
        $user = $this->auth->getUser();
        $invite_code = $user->invite_code;  //  用户邀请码
        //  拼接邀请链接界面
        $invite_url = $this->request->domain();
        $invite_url .= '/Html/te/login/register.html';
        $invite_url .= '?invite_code='.$invite_code;

        $this->success('获取成功',['invite_url' => $invite_url,'invite_code' => $invite_code]);
    }



}
